import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';

export class RvtLoader {
  constructor() {
    this.gltfLoader = new GLTFLoader();
    this.fbxLoader = new FBXLoader();
    this.objLoader = new OBJLoader();
  }

  async loadRvtFile(file) {
    try {
      // 获取文件扩展名
      const extension = file.name.split('.').pop().toLowerCase();
      
      // 创建文件的URL
      const fileURL = URL.createObjectURL(file);
      
      let model;
      
      try {
        // 根据文件类型选择合适的加载器
        switch (extension) {
          case 'gltf':
          case 'glb':
            model = await this.loadGLTF(fileURL);
            break;
          case 'fbx':
            model = await this.loadFBX(fileURL);
            break;
          case 'obj':
            model = await this.loadOBJ(fileURL);
            break;
          default:
            throw new Error('不支持的文件格式。请使用 GLTF/GLB、FBX 或 OBJ 格式的文件。');
        }
        
        // 处理加载的模型
        if (model) {
          // 计算包围盒
          const box = new THREE.Box3().setFromObject(model);
          const size = box.getSize(new THREE.Vector3());
          const center = box.getCenter(new THREE.Vector3());
          
          // 调整模型大小和位置
          const maxDim = Math.max(size.x, size.y, size.z);
          const scale = 10 / maxDim; // 将模型缩放到合适的大小
          model.scale.multiplyScalar(scale);
          
          // 将模型居中
          model.position.sub(center.multiplyScalar(scale));
          
          // 添加默认材质（如果需要）
          model.traverse((child) => {
            if (child.isMesh) {
              if (!child.material) {
                child.material = new THREE.MeshPhongMaterial({
                  color: 0x808080,
                  side: THREE.DoubleSide
                });
              }
            }
          });
        }
        
        return model;
      } finally {
        // 清理URL
        URL.revokeObjectURL(fileURL);
      }
    } catch (error) {
      console.error('加载模型时出错:', error);
      throw new Error('加载模型失败，请确保文件格式正确');
    }
  }
  
  loadGLTF(url) {
    return new Promise((resolve, reject) => {
      this.gltfLoader.load(
        url,
        (gltf) => resolve(gltf.scene),
        undefined,
        reject
      );
    });
  }
  
  loadFBX(url) {
    return new Promise((resolve, reject) => {
      this.fbxLoader.load(
        url,
        resolve,
        undefined,
        reject
      );
    });
  }
  
  loadOBJ(url) {
    return new Promise((resolve, reject) => {
      this.objLoader.load(
        url,
        resolve,
        undefined,
        reject
      );
    });
  }
} 